using SqlsugarService.Application.IService;
using SqlsugarService.Application.IService.Material;
using SqlsugarService.Application.IService.Plan;
using SqlsugarService.Application.IService.Sales;
using SqlsugarService.Application.IService.Process.BomManagement;
using SqlsugarService.Application.DTOs.PlanDto;
using SqlsugarService.Application.DTOs.SalesDto;
using SqlsugarService.Application.DTOs.Materials;
using Microsoft.Extensions.Logging;
using System.Text.Json;

namespace SqlsugarService.Application.AI.MES
{
    /// <summary>
    /// MES业务工具服务接口
    /// </summary>
    public interface IMESToolService
    {
        /// <summary>
        /// 查询生产订单
        /// </summary>
        /// <param name="parameters">查询参数</param>
        /// <returns>订单信息</returns>
        Task<object> QueryProductionOrdersAsync(Dictionary<string, object>? parameters);

        /// <summary>
        /// 查询物料库存
        /// </summary>
        /// <param name="parameters">查询参数</param>
        /// <returns>库存信息</returns>
        Task<object> QueryMaterialInventoryAsync(Dictionary<string, object>? parameters);

        /// <summary>
        /// 查询销售订单
        /// </summary>
        /// <param name="parameters">查询参数</param>
        /// <returns>销售订单信息</returns>
        Task<object> QuerySalesOrdersAsync(Dictionary<string, object>? parameters);

        /// <summary>
        /// 查询BOM信息
        /// </summary>
        /// <param name="parameters">查询参数</param>
        /// <returns>BOM信息</returns>
        Task<object> QueryBOMInfoAsync(Dictionary<string, object>? parameters);

        /// <summary>
        /// 生成生产统计报表
        /// </summary>
        /// <param name="parameters">报表参数</param>
        /// <returns>报表数据</returns>
        Task<object> GenerateProductionReportAsync(Dictionary<string, object>? parameters);

        /// <summary>
        /// 创建生产计划
        /// </summary>
        /// <param name="parameters">计划参数</param>
        /// <returns>创建结果</returns>
        Task<object> CreateProductionPlanAsync(Dictionary<string, object>? parameters);

        /// <summary>
        /// 更新订单状态
        /// </summary>
        /// <param name="parameters">更新参数</param>
        /// <returns>更新结果</returns>
        Task<object> UpdateOrderStatusAsync(Dictionary<string, object>? parameters);
    }

    /// <summary>
    /// MES业务工具服务实现
    /// </summary>
    public class MESToolService : IMESToolService
    {
        private readonly IProductionPlanService _productionPlanService;
        private readonly ISalesService _salesService;
        private readonly IMaterialService _materialService;
        private readonly IBomService _bomService;
        private readonly ILogger<MESToolService> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        public MESToolService(
            IProductionPlanService productionPlanService,
            ISalesService salesService,
            IMaterialService materialService,
            IBomService bomService,
            ILogger<MESToolService> logger)
        {
            _productionPlanService = productionPlanService ?? throw new ArgumentNullException(nameof(productionPlanService));
            _salesService = salesService ?? throw new ArgumentNullException(nameof(salesService));
            _materialService = materialService ?? throw new ArgumentNullException(nameof(materialService));
            _bomService = bomService ?? throw new ArgumentNullException(nameof(bomService));
            _logger = logger ?? throw new ArgumentNullException(nameof(logger));
        }

        /// <summary>
        /// 查询生产订单
        /// </summary>
        /// <param name="parameters">查询参数</param>
        /// <returns>订单信息</returns>
        public async Task<object> QueryProductionOrdersAsync(Dictionary<string, object>? parameters)
        {
            try
            {
                _logger.LogInformation("开始查询生产订单");

                // 解析查询参数
                var searchDto = new GetproductionplanSearchDto();
                var pageIndex = 1;
                var pageSize = 10;

                if (parameters != null)
                {
                    if (parameters.TryGetValue("pageIndex", out var pageIndexObj) && int.TryParse(pageIndexObj.ToString(), out pageIndex))
                        searchDto.PageIndex = pageIndex;

                    if (parameters.TryGetValue("pageSize", out var pageSizeObj) && int.TryParse(pageSizeObj.ToString(), out pageSize))
                        searchDto.PageSize = pageSize;

                    if (parameters.TryGetValue("planName", out var planName))
                        searchDto.PlanName = planName?.ToString();

                    if (parameters.TryGetValue("status", out var status) && int.TryParse(status?.ToString(), out var statusInt))
                        searchDto.Status = statusInt;
                }

                // 调用业务服务查询数据
                var result = await _productionPlanService.GetProductionPlanListAsync(searchDto);

                _logger.LogInformation($"生产订单查询完成，共找到 {result.Data?.TotalCount ?? 0} 条记录");

                return new
                {
                    success = true,
                    message = "查询成功",
                    data = result.Data?.Data?.Select(plan => new
                    {
                        id = plan.Id,
                        planName = plan.PlanName,
                        productName = plan.ProductName,
                        planQuantity = plan.PlanQuantity,
                        completedQuantity = plan.CompletedQuantity,
                        startDate = plan.PlanStartTime,
                        endDate = plan.PlanEndTime,
                        status = plan.Status,
                        priority = 1, // 默认优先级，因为GetproductionplanDto没有Priority属性
                        progress = plan.PlanQuantity > 0 ? (double)plan.CompletedQuantity / (double)plan.PlanQuantity * 100 : 0
                    }),
                    total = result.Data?.TotalCount ?? 0,
                    pageIndex = pageIndex,
                    pageSize = pageSize,
                    queryTime = DateTime.UtcNow
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "查询生产订单失败");
                return new
                {
                    success = false,
                    message = $"查询失败: {ex.Message}",
                    queryTime = DateTime.UtcNow
                };
            }
        }

        /// <summary>
        /// 查询物料库存
        /// </summary>
        /// <param name="parameters">查询参数</param>
        /// <returns>库存信息</returns>
        public async Task<object> QueryMaterialInventoryAsync(Dictionary<string, object>? parameters)
        {
            try
            {
                _logger.LogInformation("开始查询物料库存");

                // 解析查询参数
                string? materialCode = null;
                string? materialName = null;

                if (parameters != null)
                {
                    if (parameters.TryGetValue("materialCode", out var code))
                        materialCode = code?.ToString();

                    if (parameters.TryGetValue("materialName", out var name))
                        materialName = name?.ToString();
                }

                // 调用物料服务查询数据
                var materialsResult = await _materialService.GetMaterialListAsync();

                // 过滤结果
                var filteredMaterials = materialsResult.Data?.Data?.AsQueryable() ?? new List<MaterialSimpleDto>().AsQueryable();

                if (!string.IsNullOrEmpty(materialCode))
                    filteredMaterials = filteredMaterials.Where(m => m.MaterialNumber.Contains(materialCode));

                if (!string.IsNullOrEmpty(materialName))
                    filteredMaterials = filteredMaterials.Where(m => m.MaterialName.Contains(materialName));

                var result = filteredMaterials.Take(50).ToList(); // 限制返回数量

                _logger.LogInformation($"物料库存查询完成，共找到 {result.Count} 条记录");

                return new
                {
                    success = true,
                    message = "查询成功",
                    data = result.Select(material => new
                    {
                        id = material.Id,
                        materialCode = material.MaterialNumber,
                        materialName = material.MaterialName,
                        specification = material.SpecificationModel,
                        unit = material.Unit,
                        currentStock = 100, // 模拟当前库存
                        safetyStock = 50, // 模拟安全库存
                        categoryName = material.MaterialCategoryName ?? "未分类",
                        status = material.Status ?? "正常",
                        lastUpdated = DateTime.UtcNow.AddDays(-new Random().Next(1, 30))
                    }),
                    total = result.Count,
                    queryTime = DateTime.UtcNow
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "查询物料库存失败");
                return new
                {
                    success = false,
                    message = $"查询失败: {ex.Message}",
                    queryTime = DateTime.UtcNow
                };
            }
        }

        /// <summary>
        /// 查询销售订单
        /// </summary>
        /// <param name="parameters">查询参数</param>
        /// <returns>销售订单信息</returns>
        public async Task<object> QuerySalesOrdersAsync(Dictionary<string, object>? parameters)
        {
            try
            {
                _logger.LogInformation("开始查询销售订单");

                // 解析查询参数
                var searchDto = new GetsalesorderSearchDto();
                var pageIndex = 1;
                var pageSize = 10;

                if (parameters != null)
                {
                    if (parameters.TryGetValue("pageIndex", out var pageIndexObj) && int.TryParse(pageIndexObj.ToString(), out pageIndex))
                        searchDto.PageIndex = pageIndex;

                    if (parameters.TryGetValue("pageSize", out var pageSizeObj) && int.TryParse(pageSizeObj.ToString(), out pageSize))
                        searchDto.PageSize = pageSize;

                    if (parameters.TryGetValue("customerName", out var customerName))
                        searchDto.CustomerName = customerName?.ToString();

                    if (parameters.TryGetValue("orderStatus", out var orderStatus))
                        searchDto.OrderStatus = orderStatus?.ToString();
                }

                // 调用销售服务查询数据
                var result = await _salesService.GetsalesorderListAsync(searchDto);

                _logger.LogInformation($"销售订单查询完成，共找到 {result.Data?.TotalCount ?? 0} 条记录");

                return new
                {
                    success = true,
                    message = "查询成功",
                    data = result.Data?.Data?.Select(order => new
                    {
                        id = order.Id,
                        orderNumber = order.OrderNumber,
                        customerName = order.CustomerName,
                        customerPhone = order.CustomerPhone,
                        orderDate = order.OrderDate,
                        deliveryDate = order.DeliveryDate,
                        totalAmount = order.TotalAmount,
                        orderStatus = order.OrderStatus,
                        productCount = order.ProductName?.Split(',').Length ?? 0,
                        priority = order.Priority ?? "普通"
                    }),
                    total = result.Data?.TotalCount ?? 0,
                    pageIndex = pageIndex,
                    pageSize = pageSize,
                    queryTime = DateTime.UtcNow
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "查询销售订单失败");
                return new
                {
                    success = false,
                    message = $"查询失败: {ex.Message}",
                    queryTime = DateTime.UtcNow
                };
            }
        }

        /// <summary>
        /// 查询BOM信息
        /// </summary>
        /// <param name="parameters">查询参数</param>
        /// <returns>BOM信息</returns>
        public async Task<object> QueryBOMInfoAsync(Dictionary<string, object>? parameters)
        {
            try
            {
                _logger.LogInformation("开始查询BOM信息");

                long? productId = null;

                if (parameters != null && parameters.TryGetValue("productId", out var productIdObj))
                {
                    if (long.TryParse(productIdObj.ToString(), out var id))
                        productId = id;
                }

                if (!productId.HasValue)
                {
                    return new
                    {
                        success = false,
                        message = "缺少产品ID参数",
                        queryTime = DateTime.UtcNow
                    };
                }

                // 调用BOM服务查询数据
                var bomTree = await _bomService.GetBomTreeAsync(productId.Value);

                _logger.LogInformation($"BOM信息查询完成，产品ID: {productId}");

                return new
                {
                    success = true,
                    message = "查询成功",
                    data = new
                    {
                        productId = productId.Value,
                        bomTree = bomTree,
                        generatedAt = DateTime.UtcNow
                    },
                    queryTime = DateTime.UtcNow
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "查询BOM信息失败");
                return new
                {
                    success = false,
                    message = $"查询失败: {ex.Message}",
                    queryTime = DateTime.UtcNow
                };
            }
        }

        /// <summary>
        /// 生成生产统计报表
        /// </summary>
        /// <param name="parameters">报表参数</param>
        /// <returns>报表数据</returns>
        public async Task<object> GenerateProductionReportAsync(Dictionary<string, object>? parameters)
        {
            try
            {
                _logger.LogInformation("开始生成生产统计报表");

                // 解析报表参数
                DateTime startDate = DateTime.Today.AddDays(-30);
                DateTime endDate = DateTime.Today;
                string reportType = "summary";

                if (parameters != null)
                {
                    if (parameters.TryGetValue("startDate", out var startDateObj) && DateTime.TryParse(startDateObj.ToString(), out var start))
                        startDate = start;

                    if (parameters.TryGetValue("endDate", out var endDateObj) && DateTime.TryParse(endDateObj.ToString(), out var end))
                        endDate = end;

                    if (parameters.TryGetValue("reportType", out var type))
                        reportType = type?.ToString() ?? "summary";
                }

                // 查询生产数据
                var productionPlans = await _productionPlanService.GetProductionPlanListAsync(new GetproductionplanSearchDto
                {
                    PageIndex = 1,
                    PageSize = 1000
                });

                var salesOrders = await _salesService.GetsalesorderListAsync(new GetsalesorderSearchDto
                {
                    PageIndex = 1,
                    PageSize = 1000
                });

                // 生成统计数据
                var totalPlans = productionPlans.Data?.Data?.Count() ?? 0;
                var completedPlans = productionPlans.Data?.Data?.Count(p => p.Status == 2) ?? 0; // 已完成状态为2
                var inProgressPlans = productionPlans.Data?.Data?.Count(p => p.Status == 5) ?? 0; // 进行中状态为5
                var totalSalesOrders = salesOrders.Data?.Data?.Count() ?? 0;

                var totalPlannedQuantity = productionPlans.Data?.Data?.Sum(p => p.PlanQuantity) ?? 0;
                var totalCompletedQuantity = productionPlans.Data?.Data?.Sum(p => p.CompletedQuantity) ?? 0;

                _logger.LogInformation($"生产统计报表生成完成，统计期间: {startDate:yyyy-MM-dd} 至 {endDate:yyyy-MM-dd}");

                return new
                {
                    success = true,
                    message = "报表生成成功",
                    data = new
                    {
                        reportInfo = new
                        {
                            reportType = reportType,
                            period = $"{startDate:yyyy-MM-dd} 至 {endDate:yyyy-MM-dd}",
                            generatedAt = DateTime.UtcNow
                        },
                        summary = new
                        {
                            totalProductionPlans = totalPlans,
                            completedPlans = completedPlans,
                            inProgressPlans = inProgressPlans,
                            completionRate = totalPlans > 0 ? Math.Round((double)completedPlans / totalPlans * 100, 2) : 0,
                            totalSalesOrders = totalSalesOrders,
                            productionEfficiency = totalPlannedQuantity > 0 ? Math.Round((double)totalCompletedQuantity / (double)totalPlannedQuantity * 100, 2) : 0
                        },
                        details = new
                        {
                            dailyProduction = GenerateDailyProductionData(startDate, endDate),
                            topProducts = GenerateTopProductsData(productionPlans.Data?.Data),
                            statusDistribution = new
                            {
                                completed = completedPlans,
                                inProgress = inProgressPlans,
                                pending = totalPlans - completedPlans - inProgressPlans
                            }
                        }
                    },
                    queryTime = DateTime.UtcNow
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "生成生产统计报表失败");
                return new
                {
                    success = false,
                    message = $"报表生成失败: {ex.Message}",
                    queryTime = DateTime.UtcNow
                };
            }
        }

        /// <summary>
        /// 创建生产计划
        /// </summary>
        /// <param name="parameters">计划参数</param>
        /// <returns>创建结果</returns>
        public async Task<object> CreateProductionPlanAsync(Dictionary<string, object>? parameters)
        {
            try
            {
                _logger.LogInformation("开始创建生产计划");

                if (parameters == null)
                {
                    return new
                    {
                        success = false,
                        message = "缺少计划参数",
                        createdAt = DateTime.UtcNow
                    };
                }

                // 解析创建参数
                var createDto = new InsertupdateproductionplanDto();

                if (parameters.TryGetValue("planName", out var planName))
                    createDto.PlanName = planName?.ToString();

                if (parameters.TryGetValue("productId", out var productIdObj) && Guid.TryParse(productIdObj.ToString(), out var productId))
                    createDto.ProductId = productId;

                if (parameters.TryGetValue("planQuantity", out var quantityObj) && int.TryParse(quantityObj.ToString(), out var quantity))
                    createDto.PlanQuantity = quantity;

                if (parameters.TryGetValue("startDate", out var startDateObj) && DateTime.TryParse(startDateObj.ToString(), out var startDate))
                    createDto.StartDate = startDate;

                if (parameters.TryGetValue("endDate", out var endDateObj) && DateTime.TryParse(endDateObj.ToString(), out var endDate))
                    createDto.EndDate = endDate;

                // 设置默认值
                createDto.Status = 0; // 未分解0 已分解1 已完成2 已关闭3 已撤回4 进行中5
                createDto.Priority = 1; // 普通优先级
                createDto.CompletedQuantity = 0;
                createDto.CreatedBy = "智能助手";
                createDto.CreatedDate = DateTime.UtcNow;

                // 调用服务创建计划
                var result = await _productionPlanService.InsertProductionPlanAsync(createDto);

                _logger.LogInformation($"生产计划创建完成，计划名称: {createDto.PlanName}");

                return new
                {
                    success = result,
                    message = result ? "生产计划创建成功" : "生产计划创建失败",
                    data = result ? new
                    {
                        planName = createDto.PlanName,
                        productId = createDto.ProductId,
                        planQuantity = createDto.PlanQuantity,
                        startDate = createDto.StartDate,
                        endDate = createDto.EndDate,
                        status = createDto.Status,
                        createdBy = createDto.CreatedBy
                    } : null,
                    createdAt = DateTime.UtcNow
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "创建生产计划失败");
                return new
                {
                    success = false,
                    message = $"创建失败: {ex.Message}",
                    createdAt = DateTime.UtcNow
                };
            }
        }

        /// <summary>
        /// 更新订单状态
        /// </summary>
        /// <param name="parameters">更新参数</param>
        /// <returns>更新结果</returns>
        public async Task<object> UpdateOrderStatusAsync(Dictionary<string, object>? parameters)
        {
            try
            {
                _logger.LogInformation("开始更新订单状态");

                if (parameters == null)
                {
                    return new
                    {
                        success = false,
                        message = "缺少更新参数",
                        updatedAt = DateTime.UtcNow
                    };
                }

                Guid? orderId = null;
                string? newStatus = null;
                string orderType = "production"; // production 或 sales

                if (parameters.TryGetValue("orderId", out var orderIdObj) && Guid.TryParse(orderIdObj.ToString(), out var id))
                    orderId = id;

                if (parameters.TryGetValue("status", out var status))
                    newStatus = status?.ToString();

                if (parameters.TryGetValue("orderType", out var type))
                    orderType = type?.ToString() ?? "production";

                if (!orderId.HasValue || string.IsNullOrEmpty(newStatus))
                {
                    return new
                    {
                        success = false,
                        message = "缺少订单ID或新状态参数",
                        updatedAt = DateTime.UtcNow
                    };
                }

                bool result = false;

                if (orderType.ToLower() == "production")
                {
                    // 更新生产计划状态
                    var updateDto = new InsertupdateproductionplanDto
                    {
                        Id = orderId.Value,
                        Status = int.TryParse(newStatus, out var statusInt) ? statusInt : 0,
                        UpdatedBy = "智能助手",
                        UpdatedDate = DateTime.UtcNow
                    };

                    result = await _productionPlanService.UpdateProductionPlanAsync(updateDto);
                }
                else if (orderType.ToLower() == "sales")
                {
                    // 更新销售订单状态
                    var updateDto = new insertupdatesalesorderDto
                    {
                        Id = orderId.Value,
                        OrderStatus = newStatus,
                        UpdatedBy = "智能助手",
                        UpdatedDate = DateTime.UtcNow
                    };

                    result = await _salesService.UpdatesalesorderAsync(updateDto);
                }

                _logger.LogInformation($"订单状态更新完成，订单ID: {orderId}, 新状态: {newStatus}, 结果: {result}");

                return new
                {
                    success = result,
                    message = result ? "订单状态更新成功" : "订单状态更新失败",
                    data = result ? new
                    {
                        orderId = orderId.Value,
                        orderType = orderType,
                        newStatus = newStatus,
                        updatedBy = "智能助手"
                    } : null,
                    updatedAt = DateTime.UtcNow
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "更新订单状态失败");
                return new
                {
                    success = false,
                    message = $"更新失败: {ex.Message}",
                    updatedAt = DateTime.UtcNow
                };
            }
        }

        #region 私有方法

        /// <summary>
        /// 生成每日生产数据
        /// </summary>
        /// <param name="startDate">开始日期</param>
        /// <param name="endDate">结束日期</param>
        /// <returns>每日生产数据</returns>
        private object GenerateDailyProductionData(DateTime startDate, DateTime endDate)
        {
            var dailyData = new List<object>();
            var random = new Random();

            for (var date = startDate; date <= endDate; date = date.AddDays(1))
            {
                dailyData.Add(new
                {
                    date = date.ToString("yyyy-MM-dd"),
                    plannedQuantity = random.Next(100, 500),
                    completedQuantity = random.Next(80, 450),
                    efficiency = Math.Round(random.NextDouble() * 30 + 70, 2) // 70-100%
                });
            }

            return dailyData.TakeLast(7).ToList(); // 返回最近7天的数据
        }

        /// <summary>
        /// 生成热门产品数据
        /// </summary>
        /// <param name="productionPlans">生产计划数据</param>
        /// <returns>热门产品数据</returns>
        private object GenerateTopProductsData(IEnumerable<GetproductionplanDto>? productionPlans)
        {
            if (productionPlans == null)
                return new List<object>();

            return productionPlans
                .GroupBy(p => p.ProductName)
                .Select(g => new
                {
                    productName = g.Key,
                    totalQuantity = g.Sum(p => p.PlanQuantity),
                    completedQuantity = g.Sum(p => p.CompletedQuantity),
                    planCount = g.Count()
                })
                .OrderByDescending(p => p.totalQuantity)
                .Take(5)
                .ToList();
        }

        #endregion
    }
}